package com.yaozheng.vocationaltraining.service;

import java.io.File;

public abstract class BaseDownloadStatusListenerService implements
		DownloadStatusListenerService {
	int taskStatus;

	// String fileName;

	public int getTaskStatus() {
		return taskStatus;
	}

	// public abstract int getCompletionRate();

	public void setTashStatus(int taskStatus) {
		this.taskStatus = taskStatus;
	}

	/**
	 * 暂停
	 */
	public void pause() {
		taskStatus = PAUSE_STATUS;
	}

	/**
	 * 取消
	 */
	public synchronized void cancel() {
		int taskStatus = this.taskStatus;
		this.taskStatus = CANCEL_STATUS;
		if (taskStatus == PAUSE_STATUS) {
			notify();
		}

	}

	/**
	 * 继续下载
	 */
	public synchronized void continueDownload() {
		int taskStatus = this.taskStatus;
		this.taskStatus = DOWNLOAD_STATUS;
		if (taskStatus == PAUSE_STATUS) {
			notify();
		}

	}

	public void beginDownload() {
	}

	public void downloadSuccess() {
		taskStatus = DOWNLOAD_SUCCESS;
	}

	public void downloadError() {
		taskStatus = DOWNLOAD_ERROR;
	}

	public void endDownload(boolean runSuccess) {
		if (taskStatus == CANCEL_STATUS) {
			// File file = new File(fileName);
			// if (file.exists())
			// file.delete();
			cancelAfterRun();
			return;
		}
		if (runSuccess) {
			downloadSuccess();
		} else {
			downloadError();
		}
	}

	/**
	 * 取消之后运行
	 */
	public void cancelAfterRun() {
	}

	public synchronized boolean downloadStatusChange(double completionRate) {
		if (taskStatus == PAUSE_STATUS) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
				throw new NullPointerException(e.toString());
			}
		} else if (taskStatus == CANCEL_STATUS) {
			return false;
		}
		return true;
	}

}
